package com.hydl.power.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hydl.power.mapper.*;
import com.hydl.power.pojo.*;
import com.hydl.power.service.SendOrdersService;
import com.hydl.power.utils.CalculateDistanceUtils;
import com.hydl.power.utils.IdUtil;
import com.hydl.power.utils.PushUtils;
import com.hydl.power.utils.SmsUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class sendOrdersServiceImpl  implements SendOrdersService {


      @Autowired
      private WorkOrderMapper workOrderMapper;
      @Autowired
      private RedisTemplate redisTemplate;
      @Autowired
      private ProjectMapper projectMapper;
      @Autowired
      private OrderDeliveryMapper orderDeliveryMapper;
      @Autowired
      private PushMapper pushMapper;
      @Autowired
      private MaintainerMapper maintainerMapper;
      @Autowired
      private DeviceMapper deviceMapper;
      @Autowired
      private MarketingMapper  marketingMapper;

      @Override
      public void sendOrders(Device device) {
        if (device!=null){
          OrderDelivery orderDelivery = new OrderDelivery();
          orderDelivery.setOrderDeliveryId(IdUtil.getRandomString(8));
          orderDelivery.setOrderTypes(1);
          orderDelivery.setRank(1);
          orderDelivery.setFault("通讯中断");
          orderDelivery.setFaultTime(new Date());
          orderDelivery.setFaultTypes(4);
          //工单状态  1待派送 2待处理(派送工单) 3处理中 4 忽略工单(以忽略) 5 以结束
          orderDelivery.setOrderStatus(3);
          //是否告警 1 告警 2 不告警
          orderDelivery.setFlag(1);
          orderDelivery.setAreaId(device.getAreaId());
          orderDelivery.setAreaName(device.getAreaName());
          orderDelivery.setProjectId(device.getProjectId());
          orderDelivery.setProjectName(device.getNavId());
          orderDelivery.setRoomId(device.getPowerRoomId());
          orderDelivery.setRoomName(device.getPowerRoomName());
          orderDelivery.setDeviceId(device.getDeviceId());
          orderDelivery.setDeviceName(device.getDeviceName());
          orderDelivery.setDeviceAddress(device.getDeviceAddress());
          orderDelivery.setSn(device.getSerialNumber());

          int insert = orderDeliveryMapper.insert(orderDelivery);
          deviceMapper.updateDeviceAlarmByDeviceId(device.getDeviceId(),0,1);

          //推送
          List<String> clientIdList = pushMapper.getClientId(orderDelivery.getProjectId());
          PushUtils.sendMessage(clientIdList, orderDelivery.getRoomName(), orderDelivery.getDeviceName(), orderDelivery.getFault());

          List<Marketing> marketings = marketingMapper.queryMarketingByprojectId(device.getProjectId());


          //创建工单
              WorkOrder workOrder=new WorkOrder();
              workOrder.setOrderDeliveryId(orderDelivery.getOrderDeliveryId());
              workOrder.setOrderTypes(1);
              workOrder.setRank(1);
              workOrder.setFault("通讯中断");
              workOrder.setFaultTime(new Date());
              workOrder.setFaultTypes(4);
              workOrder.setOrderStatus(1);
              workOrder.setFlag(1);
              workOrder.setAreaId(device.getAreaId());
              workOrder.setAreaName(device.getAreaName());
              workOrder.setProjectId(device.getProjectId());
              workOrder.setProjectName(device.getNavId());
              workOrder.setRoomId(device.getPowerRoomId());
              workOrder.setRoomName(device.getPowerRoomName());
              workOrder.setDeviceId(device.getDeviceId());
              workOrder.setDeviceName(device.getDeviceName());
              workOrder.setDeviceAddress(device.getDeviceAddress());
              workOrder.setSn(device.getSerialNumber());
              workOrder.setAffirmStatus(2);
              workOrderMapper.addWorkOrder(workOrder);
          for (Marketing marketing : marketings) {
            if(marketing.getStatus() == 1){
              Maintainer maintainer = maintainerMapper.selectById1(marketing.getMaintainerId());
              workOrder.setMaintainerId(Integer.parseInt(maintainer.getMaintainerId()));
              workOrder.setMaintainerName(maintainer.getName());
              workOrder.setPhone(maintainer.getPhone());
              workOrder.setDealBeginTime(new Date());
              workOrder.setOrderDeliveryTime(new Date());
              workOrder.setOrderStatus(2);
              workOrderMapper.updateWorkOrderById(workOrder);
            }
            //发送短信
            Map<String, String> map = new HashMap<String, String>();
            map.put("projectName", workOrder.getProjectName());
            map.put("powerRoomName", workOrder.getRoomName());
            map.put("deviceName", workOrder.getDeviceName());
            map.put("fault", workOrder.getFault());
            String data = JSONObject.toJSONString(map);
            SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
          }
          orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));

              //自动派单
              WorkOrder  workOrderByProjectId = workOrderMapper.getMaintainerIdWorkOrderByProjectId(device.getProjectId());
            /*  if (workOrderByProjectId==null){
                Map<Double, String> distanceMap = new HashMap<>();
                Map<String,String> maintainerLocation = (Map<String, String>) redisTemplate.opsForValue().get("maintainerLocation");
                List<Double> distanceList = new ArrayList<>();
                Project project = projectMapper.queryProjectByProId(device.getProjectId());
                if (maintainerLocation !=null && maintainerLocation.size() > 0) {
                  for (Map.Entry<String, String> entry : maintainerLocation.entrySet()) {
                    Double distance = CalculateDistanceUtils.getDistance(entry.getValue(), project.getLongitudeLatitude() + "," + project.getLatitude_latitude(), Ellipsoid.Sphere);
                    distanceMap.put(distance, entry.getKey());
                    distanceList.add(distance);
                  }
                  Collections.sort(distanceList);
                  for (Double distance : distanceList) {
                    String maintainerId = distanceMap.get(distance);
                    List<WorkOrder> orderList = workOrderMapper.getOrderByMaintainerId(maintainerId);
                    if (orderList.size() > 0) {
                      if (orderDelivery.getProjectId().equals(orderList.get(0).getProjectId())) {
                        workOrder.setMaintainerId(orderList.get(0).getMaintainerId());
                        workOrder.setMaintainerName(orderList.get(0).getMaintainerName());
                        workOrder.setPhone(orderList.get(0).getPhone());
                        workOrder.setDealBeginTime(new Date());
                        workOrder.setOrderDeliveryTime(new Date());
                        workOrder.setOrderStatus(2);
                        for (Marketing marketing : marketings) {
                          //发送短信
                          Map<String, String> map = new HashMap<String, String>();
                          map.put("projectName", workOrder.getProjectName());
                          map.put("powerRoomName", workOrder.getRoomName());
                          map.put("deviceName", workOrder.getDeviceName());
                          map.put("fault", workOrder.getFault());
                          String data = JSONObject.toJSONString(map);
                          SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                        }
                        workOrderMapper.updateWorkOrderById(workOrder);
                        orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                        break;
                      }
                    } else {
                      Maintainer maintainer = maintainerMapper.selectById1(maintainerId);
                      //创建工单
                      workOrder.setMaintainerId(Integer.valueOf(maintainer.getMaintainerId()));
                      workOrder.setMaintainerName(maintainer.getName());
                      workOrder.setPhone(maintainer.getPhone());
                      workOrder.setDealBeginTime(new Date());
                      workOrder.setOrderDeliveryTime(new Date());
                      workOrder.setOrderStatus(2);
                      for (Marketing marketing : marketings) {
                        //发送短信
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("projectName", workOrder.getProjectName());
                        map.put("powerRoomName", workOrder.getRoomName());
                        map.put("deviceName", workOrder.getDeviceName());
                        map.put("fault", workOrder.getFault());
                        String data = JSONObject.toJSONString(map);
                        SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                      }
                      workOrderMapper.updateWorkOrderById(workOrder);
                      orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));

                      break;
                    }
                  }
                }else{
                  List<Maintainer> MaintainerList = maintainerMapper.getAll();
                  int flag=0;
                  for (Maintainer maintainer:MaintainerList){
                    if(maintainer.getMaintainerId()!=null){
                      WorkOrder workOrderByMaintainerId = workOrderMapper.getWorkOrderByMaintainerId(maintainer.getMaintainerId());
                      if(workOrderByMaintainerId==null){
                        workOrder.setMaintainerId(Integer.valueOf(maintainer.getMaintainerId()));
                        workOrder.setMaintainerName(maintainer.getName());
                        workOrder.setPhone(maintainer.getPhone());
                        workOrder.setDealBeginTime(new Date());
                        workOrder.setOrderDeliveryTime(new Date());
                        workOrder.setOrderStatus(2);
                        workOrderMapper.updateWorkOrderById(workOrder);
                        orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                        for (Marketing marketing : marketings) {
                          //发送短信
                          Map<String, String> map = new HashMap<String, String>();
                          map.put("projectName", workOrder.getProjectName());
                          map.put("powerRoomName", workOrder.getRoomName());
                          map.put("deviceName", workOrder.getDeviceName());
                          map.put("fault", workOrder.getFault());
                          String data = JSONObject.toJSONString(map);
                          SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                        }
                        flag=1;
                        break;
                      }
                    }
                  }
                  if (flag==0){
                    workOrder.setMaintainerId(94770617);
                    workOrder.setMaintainerName("张志光");
                    workOrder.setPhone("15713878160");
                    workOrder.setDealBeginTime(new Date());
                    workOrder.setOrderDeliveryTime(new Date());
                    workOrder.setOrderStatus(2);
                    workOrderMapper.updateWorkOrderById(workOrder);
                    orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                    for (Marketing marketing : marketings) {
                      //发送短信
                      Map<String, String> map = new HashMap<String, String>();
                      map.put("projectName", workOrder.getProjectName());
                      map.put("powerRoomName", workOrder.getRoomName());
                      map.put("deviceName", workOrder.getDeviceName());
                      map.put("fault", workOrder.getFault());
                      String data = JSONObject.toJSONString(map);
                      SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                    }
                  }
                }
              }*//*else{
                //创建工单
                workOrder.setMaintainerId(workOrderByProjectId.getMaintainerId());
                workOrder.setMaintainerName(workOrderByProjectId.getMaintainerName());
                workOrder.setPhone(workOrderByProjectId.getPhone());
                workOrder.setDealBeginTime(new Date());
                workOrder.setOrderDeliveryTime(new Date());
                workOrder.setOrderStatus(2);
                for (Marketing marketing : marketings) {
                  //发送短信
                  Map<String, String> map = new HashMap<String, String>();
                  map.put("projectName", workOrder.getProjectName());
                  map.put("powerRoomName", workOrder.getRoomName());
                  map.put("deviceName", workOrder.getDeviceName());
                  map.put("fault", workOrder.getFault());
                  String data = JSONObject.toJSONString(map);
                  SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                }
                workOrderMapper.updateWorkOrderById(workOrder);
                orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));


              }*/
         }
      }


  @Override
  public void sendOrdersTemperatureDevice(TemperatureDevice temperatureDevice) {
    if (temperatureDevice!=null){
      OrderDelivery orderDelivery = new OrderDelivery();
      orderDelivery.setOrderDeliveryId(IdUtil.getRandomString(8));
      orderDelivery.setOrderTypes(1);
      orderDelivery.setRank(1);
      orderDelivery.setFault("通讯中断");
      orderDelivery.setFaultTime(new Date());
      orderDelivery.setFaultTypes(4);
      //工单状态  1待派送 2待处理(派送工单) 3处理中 4 忽略工单(以忽略) 5 以结束
      orderDelivery.setOrderStatus(3);
      //是否告警 1 告警 2 不告警
      orderDelivery.setFlag(1);
      orderDelivery.setAreaId(temperatureDevice.getAreaId());
      orderDelivery.setAreaName(temperatureDevice.getAreaName());
      orderDelivery.setProjectId(temperatureDevice.getProjectId());
      orderDelivery.setProjectName(temperatureDevice.getProjectName());
      orderDelivery.setRoomId(temperatureDevice.getPowerRoomId());
      orderDelivery.setRoomName(temperatureDevice.getPowerRoomName());
      orderDelivery.setDeviceId(temperatureDevice.getDeviceId());
      orderDelivery.setDeviceName(temperatureDevice.getDeviceName());
      orderDelivery.setDeviceAddress(temperatureDevice.getDeviceAddress());
      orderDelivery.setSn(temperatureDevice.getSerialNumber());

      int insert = orderDeliveryMapper.insert(orderDelivery);
      deviceMapper.updateDeviceAlarmByDeviceId(temperatureDevice.getDeviceId(),0,1);

      //推送
      List<String> clientIdList = pushMapper.getClientId(orderDelivery.getProjectId());
      PushUtils.sendMessage(clientIdList, orderDelivery.getRoomName(), orderDelivery.getDeviceName(), orderDelivery.getFault());

      List<Marketing> marketings = marketingMapper.queryMarketingByprojectId(temperatureDevice.getProjectId());


      //创建工单
      WorkOrder workOrder=new WorkOrder();
      workOrder.setOrderDeliveryId(orderDelivery.getOrderDeliveryId());
      workOrder.setOrderTypes(1);
      workOrder.setRank(1);
      workOrder.setFault("通讯中断");
      workOrder.setFaultTime(new Date());
      workOrder.setFaultTypes(4);
      workOrder.setOrderStatus(1);
      workOrder.setFlag(1);
      workOrder.setAreaId(temperatureDevice.getAreaId());
      workOrder.setAreaName(temperatureDevice.getAreaName());
      workOrder.setProjectId(temperatureDevice.getProjectId());
      workOrder.setProjectName(temperatureDevice.getProjectName());
      workOrder.setRoomId(temperatureDevice.getPowerRoomId());
      workOrder.setRoomName(temperatureDevice.getPowerRoomName());
      workOrder.setDeviceId(temperatureDevice.getDeviceId());
      workOrder.setDeviceName(temperatureDevice.getDeviceName());
      workOrder.setDeviceAddress(temperatureDevice.getDeviceAddress());
      workOrder.setSn(temperatureDevice.getSerialNumber());
      workOrder.setAffirmStatus(2);
      workOrderMapper.addWorkOrder(workOrder);


      //自动派单
      WorkOrder  workOrderByProjectId = workOrderMapper.getMaintainerIdWorkOrderByProjectId(temperatureDevice.getProjectId());
      for (Marketing marketing : marketings) {
        if(marketing.getStatus() == 1){
          Maintainer maintainer = maintainerMapper.selectById1(marketing.getMaintainerId());
          workOrder.setMaintainerId(Integer.parseInt(maintainer.getMaintainerId()));
          workOrder.setMaintainerName(maintainer.getName());
          workOrder.setPhone(maintainer.getPhone());
          workOrder.setDealBeginTime(new Date());
          workOrder.setOrderDeliveryTime(new Date());
          workOrder.setOrderStatus(2);
          workOrderMapper.updateWorkOrderById(workOrder);
        }
        //发送短信
        Map<String, String> map = new HashMap<String, String>();
        map.put("projectName", workOrder.getProjectName());
        map.put("powerRoomName", workOrder.getRoomName());
        map.put("deviceName", workOrder.getDeviceName());
        map.put("fault", workOrder.getFault());
        String data = JSONObject.toJSONString(map);
        SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
      }
      orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
     /* if (workOrderByProjectId==null){
        Map<Double, String> distanceMap = new HashMap<>();
        Map<String,String> maintainerLocation = (Map<String, String>) redisTemplate.opsForValue().get("maintainerLocation");
        List<Double> distanceList = new ArrayList<>();
        Project project = projectMapper.queryProjectByProId(temperatureDevice.getProjectId());
        if (maintainerLocation !=null && maintainerLocation.size() > 0) {
          for (Map.Entry<String, String> entry : maintainerLocation.entrySet()) {
            Double distance = CalculateDistanceUtils.getDistance(entry.getValue(), project.getLongitudeLatitude() + "," + project.getLatitude_latitude(), Ellipsoid.Sphere);
            distanceMap.put(distance, entry.getKey());
            distanceList.add(distance);
          }
          Collections.sort(distanceList);
          for (Double distance : distanceList) {
            String maintainerId = distanceMap.get(distance);
            List<WorkOrder> orderList = workOrderMapper.getOrderByMaintainerId(maintainerId);
            if (orderList.size() > 0) {
              if (orderDelivery.getProjectId().equals(orderList.get(0).getProjectId())) {
                workOrder.setMaintainerId(orderList.get(0).getMaintainerId());
                workOrder.setMaintainerName(orderList.get(0).getMaintainerName());
                workOrder.setPhone(orderList.get(0).getPhone());
                workOrder.setDealBeginTime(new Date());
                workOrder.setOrderDeliveryTime(new Date());
                workOrder.setOrderStatus(2);
                for (Marketing marketing : marketings) {
                  //发送短信
                  Map<String, String> map = new HashMap<String, String>();
                  map.put("projectName", workOrder.getProjectName());
                  map.put("powerRoomName", workOrder.getRoomName());
                  map.put("deviceName", workOrder.getDeviceName());
                  map.put("fault", workOrder.getFault());
                  String data = JSONObject.toJSONString(map);
                  SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                }
                workOrderMapper.updateWorkOrderById(workOrder);
                orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                break;
              }
            } else {
              Maintainer maintainer = maintainerMapper.selectById1(maintainerId);
              //创建工单
              workOrder.setMaintainerId(Integer.valueOf(maintainer.getMaintainerId()));
              workOrder.setMaintainerName(maintainer.getName());
              workOrder.setPhone(maintainer.getPhone());
              workOrder.setDealBeginTime(new Date());
              workOrder.setOrderDeliveryTime(new Date());
              workOrder.setOrderStatus(2);
              for (Marketing marketing : marketings) {
                //发送短信
                Map<String, String> map = new HashMap<String, String>();
                map.put("projectName", workOrder.getProjectName());
                map.put("powerRoomName", workOrder.getRoomName());
                map.put("deviceName", workOrder.getDeviceName());
                map.put("fault", workOrder.getFault());
                String data = JSONObject.toJSONString(map);
                SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
              }
              workOrderMapper.updateWorkOrderById(workOrder);
              orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));

              break;
            }
          }
        }else{
          List<Maintainer> MaintainerList = maintainerMapper.getAll();
          int flag=0;
          for (Maintainer maintainer:MaintainerList){
            if(maintainer.getMaintainerId()!=null){
              WorkOrder workOrderByMaintainerId = workOrderMapper.getWorkOrderByMaintainerId(maintainer.getMaintainerId());
              if(workOrderByMaintainerId==null){
                workOrder.setMaintainerId(Integer.valueOf(maintainer.getMaintainerId()));
                workOrder.setMaintainerName(maintainer.getName());
                workOrder.setPhone(maintainer.getPhone());
                workOrder.setDealBeginTime(new Date());
                workOrder.setOrderDeliveryTime(new Date());
                workOrder.setOrderStatus(2);
                workOrderMapper.updateWorkOrderById(workOrder);
                orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                for (Marketing marketing : marketings) {
                  //发送短信
                  Map<String, String> map = new HashMap<String, String>();
                  map.put("projectName", workOrder.getProjectName());
                  map.put("powerRoomName", workOrder.getRoomName());
                  map.put("deviceName", workOrder.getDeviceName());
                  map.put("fault", workOrder.getFault());
                  String data = JSONObject.toJSONString(map);
                  SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                }
                flag=1;
                break;
              }
            }
          }
          if (flag==0){
            workOrder.setMaintainerId(94770617);
            workOrder.setMaintainerName("张志光");
            workOrder.setPhone("15713878160");
            workOrder.setDealBeginTime(new Date());
            workOrder.setOrderDeliveryTime(new Date());
            workOrder.setOrderStatus(2);
            workOrderMapper.updateWorkOrderById(workOrder);
            orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
            for (Marketing marketing : marketings) {
              //发送短信
              Map<String, String> map = new HashMap<String, String>();
              map.put("projectName", workOrder.getProjectName());
              map.put("powerRoomName", workOrder.getRoomName());
              map.put("deviceName", workOrder.getDeviceName());
              map.put("fault", workOrder.getFault());
              String data = JSONObject.toJSONString(map);
              SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
            }

          }
        }
      }else{
        //创建工单
        workOrder.setMaintainerId(workOrderByProjectId.getMaintainerId());
        workOrder.setMaintainerName(workOrderByProjectId.getMaintainerName());
        workOrder.setPhone(workOrderByProjectId.getPhone());
        workOrder.setDealBeginTime(new Date());
        workOrder.setOrderDeliveryTime(new Date());
        workOrder.setOrderStatus(2);
        for (Marketing marketing : marketings) {
          //发送短信
          Map<String, String> map = new HashMap<String, String>();
          map.put("projectName", workOrder.getProjectName());
          map.put("powerRoomName", workOrder.getRoomName());
          map.put("deviceName", workOrder.getDeviceName());
          map.put("fault", workOrder.getFault());
          String data = JSONObject.toJSONString(map);
          SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
        }
        workOrderMapper.updateWorkOrderById(workOrder);
        orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));

      }*/
    }
  }
}
